package demo.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * Callable+FutureTask(它是Future接口唯一的实现类)异步获取执行结果
 * @author david
 *
 */
public class CallableDemo2 {

	public static void main(String[] args) {
		CallableDemo2 demo = new CallableDemo2();
		demo.getTask();
	}
	
	public void getTask(){
		FutureTask<Integer> futureTask = new FutureTask<Integer>(new Task());
		new Thread(futureTask).start();
		
		try {
			System.out.println("主线程开始模拟做3秒钟的事情");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("主线程想要子线程的运行结果，怎么办？有办法");
		try {
			System.out.println("看看子线程返回什么："+futureTask.get());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("所有任务执行完毕");
	}
	
	class Task implements Callable<Integer> {
		public Integer call() throws Exception {
			// TODO Auto-generated method stub
			System.out.println("子线程要开始做点复杂性的事情了");
			Thread.sleep(5000);
			return 3721;
		}
		
	}
}
